package com.huawei.fakedouyin.util

import android.app.Activity
import java.util.*
import kotlin.system.exitProcess

/**
 * activity管理类
 */
class ActivityUtil {
    companion object{
        val Instance by lazy { ActivityUtil() }
    }

    private val mActivityStack = Stack<Activity>()

    fun addActivity(activity: Activity) {
        mActivityStack.add(activity)
    }

    fun removeActivity(activity: Activity) {
        if (mActivityStack.contains(activity)) {
            mActivityStack.remove(activity)
        }
    }


    fun activityCount() = mActivityStack.size

    /**
     * 栈顶activity
     */
    fun getCurrentActivity(): Activity? {
        if (mActivityStack.isEmpty()) {
            return null
        }
        return mActivityStack.lastElement()
    }

    fun getActivity(clz: Class<*>): Activity? {
        for (activity: Activity in mActivityStack) {
            if (activity.javaClass == clz) {
                return activity
            }
        }
        return null
    }

    /**
     * 结束某activity
     */
    fun finishActivity(activity: Activity?) {
        if (mActivityStack.contains(activity)) {
            mActivityStack.remove(activity)
        }
        activity?.finish()
    }


    fun getAllActivity(): Stack<Activity> {
        return mActivityStack
    }

    fun finishAllActivity() {
        for (value in mActivityStack.size - 1 downTo 0) {
            finishActivity(mActivityStack[value])
        }

        mActivityStack.clear()
    }
    fun finishAllActivityExceptLastOne() {
        for (value in mActivityStack.size - 1 downTo 0) {
            if (value != mActivityStack.size - 1) {
                finishActivity(mActivityStack[value])
            }
        }
    }

    fun finishCurrentActivity() {
        finishActivity(getCurrentActivity())
    }

    fun exitApp() {
        try {
            finishAllActivity()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            exitProcess(0)
        }
    }
}